package com.inei.cenacom.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.inei.cenacom.R;
import com.inei.cenacom.controller.CaratulaController;
import com.inei.cenacom.controller.UbigeoController;
import com.inei.cenacom.model.entity.Caratula;
import com.inei.cenacom.model.entity.Departamento;
import com.inei.cenacom.model.entity.Distrito;
import com.inei.cenacom.model.entity.Provincia;
import com.inei.cenacom.tools.Mensaje;
import com.inei.cenacom.tools.OnSiguienteListener;
import com.inei.cenacom.tools.Validacion;

public class Caratula_1_Fragment extends Fragment {

	private TextView tvCAPI;
	private EditText et1, et2, et3, etC1_4, etC1_5, etC1_6, etC1_7, etC1_5_1,
			etC1_6_1, etC1_7_1, etC1_9, etC1_9_1, etC1_9_2, etC1_9_3, etC1_9_4,
			etC1_9_5, etC1_9_6, etC1_9_7, etC1_10;
	private Spinner spC1_1, spC1_2, spC1_3, spC1_8;
	private UbigeoController uCon;
	private CaratulaController cCon;
	private Caratula c;
	private List<Departamento> lDep;
	private List<Provincia> lPro;
	private List<Distrito> lDis;
	private int pro;
	private int dis;
	private int vez;
	private String ccdd;
	private String ccpp;
	private Mensaje m;
	private Validacion v;
	private Button bSiguiente1;
	private OnSiguienteListener onSiguienteListener;

	public OnSiguienteListener getOnSiguienteListener() {
		return onSiguienteListener;
	}

	public void setOnSiguienteListener(OnSiguienteListener onSiguienteListener) {
		this.onSiguienteListener = onSiguienteListener;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment_caratula_1, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		uCon = new UbigeoController(getActivity());
		cCon = new CaratulaController(getActivity());
		m = new Mensaje(getActivity());
		v = new Validacion(m);

		pro = 0;
		dis = 0;
		vez = 0;
		iniciarComponentes();
		agregarEventos();
		cargarDatos();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		vez = 0;
		TimerTask task = new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				vez = 0;
			}
		};
		Timer timer = new Timer();
		timer.schedule(task, 2000);

	}

	private void agregarEventos() {
		// TODO Auto-generated method stub
		spC1_1.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				Provincia prov = new Provincia();
				prov.setCcdd("00");
				prov.setCcpp("00");
				prov.setNom_prov("Seleccionar Provincia");
				if (pos != 0) {
					ccdd = ((Departamento) spC1_1.getItemAtPosition(pos))
							.getCcdd();
					lPro = uCon.leerPro(ccdd);
					lPro.add(0, prov);
					spC1_2.setAdapter(new ArrayAdapter<Provincia>(
							getActivity(),
							android.R.layout.simple_spinner_dropdown_item, lPro));
					if (c != null && pro == 0) {
						for (int i = 0; i < lPro.size(); i++) {
							if (c.getCCPP().equals(lPro.get(i).getCcpp())) {
								spC1_2.setSelection(i);

								break;
							}
						}
						pro = 1;
					}
				} else {
					lPro = new ArrayList<Provincia>();
					lPro.add(0, prov);
					spC1_2.setAdapter(new ArrayAdapter<Provincia>(
							getActivity(),
							android.R.layout.simple_spinner_dropdown_item, lPro));
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		spC1_2.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				if (vez == 0) {
					Log.i("DIS", "ENTRO 0");
					Distrito dist = new Distrito();
					dist.setCcdd("00");
					dist.setCcpp("00");
					dist.setCcdi("00");
					dist.setNom_dist("Seleccionar Distrito");
					if (pos != 0) {
						Log.i("DIS", "ENTRO 1");
						Log.i("DIS", "ccdd " + ccdd + " ccpp " + ccpp);
						ccpp = ((Provincia) lPro.get(pos)).getCcpp();
						lDis = uCon.leerDis(ccdd, ccpp);
						lDis.add(0, dist);
						spC1_3.setAdapter(new ArrayAdapter<Distrito>(
								getActivity(),
								android.R.layout.simple_spinner_dropdown_item,
								lDis));
						Log.i("DIS", "ENTRO 2");
						Log.i("DIS", "ccdd " + ccdd + " ccpp " + ccpp);
						if (c != null && dis == 0) {
							Log.i("DIS", "ENTRO 3");
							for (int i = 0; i < lDis.size(); i++) {
								if (c.getCCDI().equals(lDis.get(i).getCcdi())) {
									Log.i("DIS", "ENTRO 4");
									spC1_3.setSelection(i);
									Log.i("TAG: ", "" + i);
									vez = 1;
									break;
								}
							}
							dis = 1;
						}
					} else {
						lDis = new ArrayList<Distrito>();
						lDis.add(0, dist);
						spC1_3.setAdapter(new ArrayAdapter<Distrito>(
								getActivity(),
								android.R.layout.simple_spinner_dropdown_item,
								lDis));
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		etC1_5.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence texto, int start,
					int before, int count) {
				// TODO Auto-generated method stub
				if (texto.toString().length() != 0) {
					etC1_7.setText("");
					etC1_7.setEnabled(false);
					etC1_7_1.setText("");
					etC1_7_1.setEnabled(false);
				} else {
					if (etC1_5_1.getText().toString().isEmpty()
							&& etC1_6.getText().toString().isEmpty()
							&& etC1_6_1.getText().toString().isEmpty()) {
						etC1_7.setEnabled(true);
						etC1_7_1.setEnabled(true);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		etC1_5_1.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence texto, int start,
					int before, int count) {
				// TODO Auto-generated method stub
				if (texto.toString().length() != 0) {
					etC1_7.setText("");
					etC1_7.setEnabled(false);
					etC1_7_1.setText("");
					etC1_7_1.setEnabled(false);
				} else {
					if (etC1_5.getText().toString().isEmpty()
							&& etC1_6.getText().toString().isEmpty()
							&& etC1_6_1.getText().toString().isEmpty()) {
						etC1_7.setEnabled(true);
						etC1_7_1.setEnabled(true);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		etC1_6.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence texto, int start,
					int before, int count) {
				// TODO Auto-generated method stub
				if (texto.toString().length() != 0) {
					etC1_7.setText("");
					etC1_7.setEnabled(false);
					etC1_7_1.setText("");
					etC1_7_1.setEnabled(false);
				} else {
					if (etC1_5.getText().toString().isEmpty()
							&& etC1_6_1.getText().toString().isEmpty()
							&& etC1_5_1.getText().toString().isEmpty()) {
						etC1_7.setEnabled(true);
						etC1_7_1.setEnabled(true);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		etC1_6_1.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence texto, int start,
					int before, int count) {
				// TODO Auto-generated method stub
				if (texto.toString().length() != 0) {
					etC1_7.setText("");
					etC1_7.setEnabled(false);
					etC1_7_1.setText("");
					etC1_7_1.setEnabled(false);
				} else {
					if (etC1_5.getText().toString().isEmpty()
							&& etC1_6.getText().toString().isEmpty()
							&& etC1_5_1.getText().toString().isEmpty()) {
						etC1_7.setEnabled(true);
						etC1_7_1.setEnabled(true);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		etC1_7.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence texto, int start,
					int before, int count) {
				// TODO Auto-generated method stub
				if (texto.toString().length() != 0) {
					etC1_5.setText("");
					etC1_5_1.setText("");
					etC1_6.setText("");
					etC1_6_1.setText("");
					etC1_5.setEnabled(false);
					etC1_5_1.setEnabled(false);
					etC1_6.setEnabled(false);
					etC1_6_1.setEnabled(false);
				} else {
					if (etC1_7_1.getText().toString().isEmpty()) {

						etC1_5.setEnabled(true);
						etC1_5_1.setEnabled(true);
						etC1_6.setEnabled(true);
						etC1_6_1.setEnabled(true);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		etC1_7_1.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence texto, int start,
					int before, int count) {
				// TODO Auto-generated method stub
				if (texto.toString().length() != 0) {
					etC1_5.setText("");
					etC1_5_1.setText("");
					etC1_6.setText("");
					etC1_6_1.setText("");
					etC1_5.setEnabled(false);
					etC1_5_1.setEnabled(false);
					etC1_6.setEnabled(false);
					etC1_6_1.setEnabled(false);
				} else {
					if (etC1_7.getText().toString().isEmpty()) {

						etC1_5.setEnabled(true);
						etC1_5_1.setEnabled(true);
						etC1_6.setEnabled(true);
						etC1_6_1.setEnabled(true);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		
		
		spC1_8.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int pos, long arg3) {
				// TODO Auto-generated method stub
				if(pos!=0){
					etC1_9.requestFocus();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
	}

	private void iniciarComponentes() {
		tvCAPI = (TextView) getView().findViewById(R.id.tvCAPI);
		int anio = getArguments().getInt("ANIO");
		if (anio == 2011) {
			tvCAPI.setBackgroundColor(getActivity().getResources().getColor(
					R.color.Azul));
			tvCAPI.setTextColor(Color.WHITE);
		}
		bSiguiente1 = (Button) getView().findViewById(R.id.bSiguiente1);
		bSiguiente1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (onSiguienteListener != null) {
					onSiguienteListener.OnSiguiente(1);
				}
			}
		});
		et1 = (EditText) getView().findViewById(R.id.et1);
		et1.setFocusable(false);
		et2 = (EditText) getView().findViewById(R.id.et2);
		et2.setFocusable(false);
		et3 = (EditText) getView().findViewById(R.id.et3);
		et3.setFocusable(false);
		etC1_4 = (EditText) getView().findViewById(R.id.etC1_4);
		etC1_5 = (EditText) getView().findViewById(R.id.etC1_5);
		etC1_6 = (EditText) getView().findViewById(R.id.etC1_6);
		etC1_7 = (EditText) getView().findViewById(R.id.etC1_7);
		etC1_5_1 = (EditText) getView().findViewById(R.id.etC1_5_1);
		etC1_6_1 = (EditText) getView().findViewById(R.id.etC1_6_1);
		etC1_7_1 = (EditText) getView().findViewById(R.id.etC1_7_1);
		etC1_9 = (EditText) getView().findViewById(R.id.etC1_9);
		etC1_9_1 = (EditText) getView().findViewById(R.id.etC1_9_1);
		etC1_9_2 = (EditText) getView().findViewById(R.id.etC1_9_2);
		etC1_9_3 = (EditText) getView().findViewById(R.id.etC1_9_3);
		etC1_9_4 = (EditText) getView().findViewById(R.id.etC1_9_4);
		etC1_9_5 = (EditText) getView().findViewById(R.id.etC1_9_5);
		etC1_9_6 = (EditText) getView().findViewById(R.id.etC1_9_6);
		etC1_9_7 = (EditText) getView().findViewById(R.id.etC1_9_7);
		etC1_10 = (EditText) getView().findViewById(R.id.etC1_10);

		spC1_1 = (Spinner) getView().findViewById(R.id.spC1_1);
		spC1_1.setPressed(true);
		spC1_2 = (Spinner) getView().findViewById(R.id.spC1_2);
		spC1_3 = (Spinner) getView().findViewById(R.id.spC1_3);
		spC1_8 = (Spinner) getView().findViewById(R.id.spC1_8);

		lDep = uCon.leerDep();
		Departamento depa = new Departamento();
		depa.setCcdd("00");
		depa.setNom_dpto("Seleccionar Departamento");
		lDep.add(0, depa);
		ArrayAdapter<Departamento> adapterDD = new ArrayAdapter<Departamento>(
				getActivity(), android.R.layout.simple_spinner_dropdown_item,
				lDep);
		spC1_1.setAdapter(adapterDD);

		ccdd = "00";
		ccpp = "00";
	}

	private void cargarDatos() {
		Bundle b = getArguments();
		if (b != null) {
			c = new Caratula();
			c.setID_N(b.getString("ID_N"));
			c.setANIO(b.getInt("ANIO"));
			c = cCon.buscar(c);
			if (c == null) {
				c = new Caratula();
				c.setID_N(b.getString("ID_N"));
				c.setANIO(b.getInt("ANIO"));
				c.setCCDD(b.getString("CCDD"));
				c.setCCPP(b.getString("CCPP"));
				c.setCCDI(b.getString("CCDI"));
				c.setZONA(b.getString("ZONA"));
				c.setZONAALF(b.getString("ZONALF"));
				c.setMZA(b.getString("MANZANA"));
				c.setMZAALF(b.getString("MZNALF"));
				c.setAER_INI(b.getString("AER_INI"));
				c.setAER_FIN(b.getString("AER_FIN"));
				
				c.setDPTO_ASIG(b.getString("DEP_ASIG"));
				c.setRUTA(b.getString("RUTA"));
				c.setUSR_CREACION(b.getString("USUARIO"));
				c.setUSR_EDICION(b.getString("USUARIO"));
				
				
				
				int r = cCon.crear(c);
				if (r == -1) {
					m.Error("No se pudo crear");
				} else {
					et1.setText(c.getID_N());
					et2.setText(c.getRUTA());
					et3.setText(c.getDPTO_ASIG());
					etC1_5.setText(c.getZONA());
					etC1_5_1.setText(c.getZONAALF());
					etC1_6.setText(c.getMZA());
					etC1_6_1.setText(c.getMZAALF());
					etC1_7.setText(c.getAER_INI());
					etC1_7_1.setText(c.getAER_FIN());
					if (c.getCCDD() != null) {
						for (int i = 0; i < lDep.size(); i++) {
							if (c.getCCDD().equals(lDep.get(i).getCcdd())) {
								spC1_1.setSelection(i);
								break;
							}
						}
					}
					// spC1_1.setSelection(Integer.parseInt(c.getCCDD()));
				}
			} else {
				c.setUSR_EDICION(b.getString("USUARIO"));				
				et1.setText(c.getID_N());
				et2.setText(c.getRUTA());
				et3.setText(c.getDPTO_ASIG());
				if (c.getCCDD() != null) {
					for (int i = 0; i < lDep.size(); i++) {
						if (c.getCCDD().equals(lDep.get(i).getCcdd())) {
							spC1_1.setSelection(i);
							break;
						}
					}
				}
				// spC1_1.setSelection(Integer.parseInt(c.getCCDD()));

				etC1_4.setText(c.getNOMBRE_CP());
				spC1_8.setSelection(c.getI9_1());
				etC1_9.setText(c.getI9_2());
				etC1_9_1.setText(c.getI9_4());
				etC1_9_2.setText(c.getI9_5());
				etC1_9_3.setText(c.getI9_6());
				etC1_9_4.setText(c.getI9_7());
				etC1_9_5.setText(c.getI9_8());
				etC1_9_6.setText(c.getI9_9() != 0.0 ? c.getI9_9() + "" : "");

				etC1_9_7.setText(c.getI9_10());
				etC1_10.setText(c.getI9_3());

				etC1_5.setText(c.getZONA());
				etC1_5_1.setText(c.getZONAALF());
				etC1_6.setText(c.getMZA());
				etC1_6_1.setText(c.getMZAALF());
				etC1_7.setText(c.getAER_INI());
				etC1_7_1.setText(c.getAER_FIN());
			}
		}
	}

	public Caratula guardar() throws Exception {
		if (!v.validarSpinner(spC1_1, true, 0, null)) {
			throw new Exception();
		} else if (!v.validarSpinner(spC1_2, true, 0, null)) {
			throw new Exception();
		} else if (!v.validarSpinner(spC1_3, true, 0, null)) {
			throw new Exception();
		} else if (!v.validarTextoAN(etC1_4, false)) {
			throw new Exception();
		} else if (!v.validarSpinner(spC1_8, true, 0, null)) {
			throw new Exception();
		} else if (!v.validarTextoAN(etC1_9, true)) {
			throw new Exception();
		} else if (!v.validarTextoAN(etC1_9_1, true)) {
			throw new Exception();
		} else if (!v.validarTextoAN(etC1_9_2, false)) {
			throw new Exception();
		} else if (!v.validarPiso(etC1_9_3, true)) {
			throw new Exception();
		} else if (!v.validarTextoAN(etC1_9_4, false)) {
			throw new Exception();
		} else if (!v.validarTextoAN(etC1_9_5, false)) {
			throw new Exception();
		} else if (!v.validarTextoN2(etC1_9_6, false)) {
			throw new Exception();
		} else if (!v.validarTelefono(etC1_9_7, true)) {
			throw new Exception();
		} else if (!v.validarTextoAN(etC1_10, true)) {
			throw new Exception();
		} else if (!validarCartografia()) {
			throw new Exception();
		} else {
			c.setCCDD(lDep.get(spC1_1.getSelectedItemPosition()).getCcdd());
			c.setCCPP(lPro.get(spC1_2.getSelectedItemPosition()).getCcpp());
			c.setCCDI(lDis.get(spC1_3.getSelectedItemPosition()).getCcdi());
			c.setNOMBRE_CP(etC1_4.getText().toString());
			c.setI9_1(spC1_8.getSelectedItemPosition());
			c.setI9_2(etC1_9.getText().toString());
			c.setI9_4(etC1_9_1.getText().toString());
			c.setI9_5(etC1_9_2.getText().toString());
			c.setI9_6(etC1_9_3.getText().toString());
			c.setI9_7(etC1_9_4.getText().toString());
			c.setI9_8(etC1_9_5.getText().toString());
			c.setI9_9(Double
					.parseDouble(etC1_9_6.getText().toString().length() == 0 ? "0.0"
							: etC1_9_6.getText().toString()));
			c.setI9_10(etC1_9_7.getText().toString());
			c.setI9_3(etC1_10.getText().toString());
			c.setZONA(etC1_5.getText().toString());
			c.setZONAALF(etC1_5_1.getText().toString());
			c.setMZA(etC1_6.getText().toString());
			c.setMZAALF(etC1_6_1.getText().toString());
			c.setAER_INI(etC1_7.getText().toString());
			c.setAER_FIN(etC1_7_1.getText().toString());
			return c;
		}
	}

	public boolean validarCartografia() {
		if (etC1_5.getText().toString().isEmpty()
				&& etC1_5_1.getText().toString().isEmpty()
				&& etC1_6.getText().toString().isEmpty()
				&& etC1_6_1.getText().toString().isEmpty()
				&& etC1_7.getText().toString().isEmpty()
				&& etC1_7.getText().toString().isEmpty()) {
			m.Error("Debe ingresar la zona y manzana o el AER");
			etC1_5.requestFocus();
			return false;
		} else if (!etC1_7.getText().toString().isEmpty()
				|| !etC1_7.getText().toString().isEmpty()) {
			if (!v.validarTextoAN(etC1_7, true)) {
				return false;
			} else if (!v.validarAER(etC1_7)) {
				return false;
			} else if (!v.validarTextoAN(etC1_7_1, true)) {
				return false;
			} else if (!v.validarAER(etC1_7_1)) {
				return false;
			}
		} else {
			if (!v.validarTextoAN(etC1_5, true)) {
				return false;
			} else if (!v.validarZONA(etC1_5)) {
				return false;
			} else if (!v.validarTextoA(etC1_5_1, false)) {
				return false;
			} else if (!v.validarTextoAN(etC1_6, true)) {
				return false;
			} else if (!v.validarMZA(etC1_6)) {
				return false;
			} else if (!v.validarTextoA(etC1_6_1, false)) {
				return false;
			}
		}

		return true;
	}

}
